<template>
  <div class="upload-form">
    <a-form ref="formRef" :model="formData" :rules="rules" layout="vertical" @finish="handleSubmit">
      <!-- 文件上传 -->
      <a-form-item label="选择图片">
        <a-upload-dragger
          v-model:file-list="fileList"
          :before-upload="beforeUpload"
          :custom-request="customUpload"
          :multiple="false"
          :max-count="1"
          accept="image/*"
          :show-upload-list="false"
          @preview="handlePreview"
        >
          <!-- 没有文件时显示上传提示 -->
          <div v-if="!currentFile" class="upload-area">
            <p class="ant-upload-drag-icon">
              <InboxOutlined style="font-size: 48px; color: #1890ff" />
            </p>
            <p class="ant-upload-text">点击或拖拽图片到此区域上传</p>
            <p class="ant-upload-hint">支持 JPG、PNG、GIF、WebP 格式，文件大小不超过 10MB</p>
            <p class="ant-upload-hint-ai">
              上传后AI将自动生成图片标题、标签和分类，您可以选择性修改
            </p>
          </div>

          <!-- 有文件时显示预览 -->
          <div v-else class="upload-preview">
            <div class="preview-image-container">
              <img
                v-if="fileList.length > 0"
                :src="fileList[0].url"
                :alt="fileList[0].name"
                class="preview-image"
              />
            </div>
            <div class="preview-info">
              <p class="preview-filename">{{ currentFile.name }}</p>
              <p class="preview-size">{{ formatFileSize(currentFile.size) }}</p>
              <p class="preview-hint">点击重新选择图片</p>
            </div>
          </div>
        </a-upload-dragger>
      </a-form-item>

      <!-- 提交按钮 -->
      <a-form-item class="form-actions">
        <a-space>
          <a-button type="primary" html-type="submit" :loading="uploading" size="large">
            <template #icon>
              <CloudUploadOutlined />
            </template>
            {{ uploading ? '上传中...' : '上传图片' }}
          </a-button>
          <a-button @click="handleCancel" size="large"> 取消 </a-button>
        </a-space>
      </a-form-item>
    </a-form>

    <!-- 图片预览模态框 -->
    <a-modal v-model:open="previewVisible" title="图片预览" :footer="null" centered>
      <img :src="previewImage" :alt="previewTitle" style="width: 100%" />
    </a-modal>

    <!-- AI生成内容编辑弹窗 -->
    <a-modal
      v-model:open="editModalVisible"
      title="编辑图片信息"
      width="600px"
      :confirm-loading="editLoading"
      @ok="handleEditSubmit"
      @cancel="handleEditCancel"
    >
      <div class="edit-modal-content">
        <a-alert
          message="AI已为您生成图片信息"
          description="您可以对AI生成的标题、简介、分类和标签进行修改，或直接保存使用。"
          type="info"
          show-icon
          style="margin-bottom: 20px"
        />

        <a-form ref="editFormRef" :model="editFormData" layout="vertical">
          <!-- 图片预览 -->
          <div class="uploaded-image-preview" v-if="uploadedImageUrl">
            <img :src="uploadedImageUrl" alt="上传的图片" />
          </div>

          <!-- 图片名称 -->
          <a-form-item label="图片标题" name="name">
            <a-input
              v-model:value="editFormData.name"
              placeholder="请输入图片标题"
              :max-length="100"
              show-count
            />
          </a-form-item>

          <!-- 图片简介 -->
          <a-form-item label="图片简介" name="introduction">
            <a-textarea
              v-model:value="editFormData.introduction"
              placeholder="请输入图片简介"
              :rows="3"
              :max-length="500"
              show-count
            />
          </a-form-item>

          <!-- 图片分类 -->
          <a-form-item label="图片分类" name="category">
            <a-select
              v-model:value="editFormData.category"
              placeholder="请选择或输入图片分类"
              :options="categoryOptions"
              allow-clear
              show-search
              :filter-option="filterOption"
              @search="handleCategorySearch"
            >
              <template #notFoundContent>
                <div style="padding: 4px 8px">
                  <a-button type="link" size="small" @click="addNewCategory">
                    + 添加新分类 "{{ categorySearchValue }}"
                  </a-button>
                </div>
              </template>
            </a-select>
          </a-form-item>

          <!-- 图片标签 -->
          <a-form-item label="图片标签" name="tags">
            <a-select
              v-model:value="editFormData.tags"
              mode="tags"
              placeholder="请选择或输入图片标签"
              :options="tagOptions"
              :max-tag-count="10"
              :filter-option="filterOption"
              @search="handleTagSearch"
            >
              <template #maxTagPlaceholder="omittedValues">
                <span style="color: #999">+{{ omittedValues.length }} 更多</span>
              </template>
            </a-select>
          </a-form-item>
        </a-form>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import type { FormInstance, UploadFile } from 'ant-design-vue'
import { message } from 'ant-design-vue'
import { CloudUploadOutlined, InboxOutlined } from '@ant-design/icons-vue'
import { editPicture, listPictureTagCategory, uploadPicture } from '@/api/picture'
import type { PictureUploadRequest } from '@/types/picture'
import type { FileType } from 'ant-design-vue/es/upload/interface'

// 定义事件
const emit = defineEmits<{
  success: []
  cancel: []
}>()

// 响应式数据
const formRef = ref<FormInstance>()
const editFormRef = ref<FormInstance>()
const uploading = ref(false)
const editLoading = ref(false)
const fileList = ref<UploadFile[]>([])
const previewVisible = ref(false)
const previewImage = ref('')
const previewTitle = ref('')
const categorySearchValue = ref('')
const tagSearchValue = ref('')

// 编辑弹窗相关
const editModalVisible = ref(false)
const uploadedImageUrl = ref('')
const uploadedPictureId = ref<string | null>(null)

// 当前选择的文件（用于上传）
const currentFile = ref<File | null>(null)

// 表单数据
const formData = reactive({
  // 移除了原有的表单字段，现在只需要文件
})

// 编辑表单数据
const editFormData = reactive({
  name: '',
  introduction: '',
  category: '',
  tags: [] as string[],
})

// 标签和分类选项
const categoryList = ref<string[]>([])
const tagList = ref<string[]>([])

// 计算属性
const categoryOptions = computed(() =>
  categoryList.value.map((category) => ({ label: category, value: category })),
)

const tagOptions = computed(() => tagList.value.map((tag) => ({ label: tag, value: tag })))

// 表单验证规则（现在不需要了，因为我们手动验证文件）
const rules = {}

// 初始化数据
onMounted(async () => {
  await loadTagsAndCategories()
})

// 加载标签和分类
const loadTagsAndCategories = async () => {
  try {
    const response = await listPictureTagCategory()
    if (response.data) {
      categoryList.value = response.data.categoryList || []
      tagList.value = response.data.tagList || []
    }
  } catch (error) {
    console.error('加载标签和分类失败:', error)
  }
}

// 文件上传前检查
const beforeUpload = (file: File) => {
  // 检查文件类型
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    message.error('只能上传图片文件！')
    return false
  }

  // 检查文件大小 (10MB)
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    message.error('图片大小不能超过 10MB！')
    return false
  }

  // 保存当前文件用于上传
  currentFile.value = file

  // 创建预览URL
  const reader = new FileReader()
  reader.onload = (e) => {
    const uploadFile: UploadFile = {
      uid: Date.now().toString(),
      name: file.name,
      status: 'done',
      url: e.target?.result as string,
      originFileObj: file as FileType, // 临时解决类型问题
    }
    fileList.value = [uploadFile]
  }
  reader.readAsDataURL(file)

  return false // 阻止自动上传
}

// 自定义上传处理
const customUpload = ({
  file,
  onSuccess,
}: {
  file: UploadFile
  onSuccess: (file: UploadFile) => void
}) => {
  // 这里不实际上传，只是添加到文件列表
  onSuccess(file)
}

// 图片预览
const handlePreview = (file: UploadFile) => {
  previewImage.value = file.url || file.thumbUrl || ''
  previewTitle.value = file.name || ''
  previewVisible.value = true
}

// 过滤选项
const filterOption = (input: string, option: { label: string }) => {
  return option.label.toLowerCase().includes(input.toLowerCase())
}

// 分类搜索
const handleCategorySearch = (value: string) => {
  categorySearchValue.value = value
}

// 标签搜索
const handleTagSearch = (value: string) => {
  tagSearchValue.value = value
}

// 添加新分类
const addNewCategory = () => {
  const newCategory = categorySearchValue.value.trim()
  if (newCategory && !categoryList.value.includes(newCategory)) {
    categoryList.value.push(newCategory)
    editFormData.category = newCategory
  }
}

// 格式化文件大小
const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 表单提交
const handleSubmit = async () => {
  console.log('handleSubmit被调用')
  console.log('currentFile.value:', currentFile.value)

  if (!currentFile.value) {
    message.error('请选择要上传的图片')
    return
  }

  uploading.value = true
  try {
    // 构建上传请求参数，只传递必要参数
    const request: PictureUploadRequest = {}

    console.log('开始上传图片:', currentFile.value.name)
    console.log('文件大小:', currentFile.value.size)
    console.log('文件类型:', currentFile.value.type)

    // 上传图片
    const response = await uploadPicture(currentFile.value, request)

    console.log('上传响应:', response)

    if (response.data) {
      // 保存上传结果
      uploadedPictureId.value = response.data.id
      uploadedImageUrl.value = response.data.url || ''

      // 用AI生成的内容填充编辑表单
      editFormData.name = response.data.name || ''
      editFormData.introduction = response.data.introduction || ''
      editFormData.category = response.data.category || ''
      editFormData.tags = response.data.tags || []

      message.success('图片上传成功！AI正在生成图片信息...')

      // 显示编辑弹窗
      editModalVisible.value = true
    }
  } catch (error: unknown) {
    console.error('上传失败详细信息:', error)
    console.error('错误响应:', (error as unknown as { response: unknown }).response)
    message.error('图片上传失败，请重试')
  } finally {
    uploading.value = false
  }
}

// 取消上传
const handleCancel = () => {
  emit('cancel')
  resetForm()
}

// 编辑弹窗提交
const handleEditSubmit = async () => {
  if (!uploadedPictureId.value) {
    message.error('图片ID不存在')
    return
  }

  editLoading.value = true
  try {
    await editPicture({
      id: uploadedPictureId.value,
      name: editFormData.name || undefined,
      introduction: editFormData.introduction || undefined,
      category: editFormData.category || undefined,
      tags: editFormData.tags.length > 0 ? editFormData.tags : undefined,
    })

    message.success('图片信息保存成功！')
    editModalVisible.value = false
    emit('success')
    resetForm()
  } catch (error: unknown) {
    console.error('编辑失败:', error)
    message.error('保存图片信息失败，请重试')
  } finally {
    editLoading.value = false
  }
}

// 编辑弹窗取消
const handleEditCancel = () => {
  editModalVisible.value = false
  // 可以选择是否删除已上传的图片
  // 这里暂时不删除，让用户可以重新编辑
}

// 重置表单
const resetForm = () => {
  formRef.value?.resetFields()
  editFormRef.value?.resetFields()
  fileList.value = []
  currentFile.value = null

  // 重置编辑表单数据
  editFormData.name = ''
  editFormData.introduction = ''
  editFormData.category = ''
  editFormData.tags = []

  // 重置上传相关状态
  uploadedPictureId.value = null
  uploadedImageUrl.value = ''
  editModalVisible.value = false
}
</script>

<style scoped>
.upload-form {
  max-width: 100%;
}

.upload-area {
  padding: 40px 20px;
  text-align: center;
}

.form-actions {
  margin-top: 24px;
  text-align: center;
}

:deep(.ant-upload-drag) {
  border-radius: 8px;
  border: 2px dashed #d9d9d9;
  transition: border-color 0.3s ease;
}

:deep(.ant-upload-drag:hover) {
  border-color: #1890ff;
}

:deep(.ant-upload-drag.ant-upload-drag-hover) {
  border-color: #1890ff;
}

:deep(.ant-upload-text) {
  font-size: 16px;
  font-weight: 500;
  color: #262626;
  margin: 16px 0 8px 0;
}

:deep(.ant-upload-hint) {
  font-size: 14px;
  color: #999;
  margin: 0;
}

.ant-upload-hint-ai {
  font-size: 12px;
  color: #52c41a !important;
  margin: 8px 0 0 0 !important;
  font-weight: 500;
}

.upload-preview {
  display: flex;
  align-items: center;
  padding: 20px;
  gap: 16px;

  .preview-image-container {
    flex-shrink: 0;

    .preview-image {
      width: 120px;
      height: 120px;
      object-fit: cover;
      border-radius: 8px;
      border: 1px solid #d9d9d9;
    }
  }

  .preview-info {
    flex: 1;
    text-align: left;

    .preview-filename {
      font-size: 16px;
      font-weight: 500;
      color: #262626;
      margin: 0 0 8px 0;
      word-break: break-all;
    }

    .preview-size {
      font-size: 14px;
      color: #8c8c8c;
      margin: 0 0 8px 0;
    }

    .preview-hint {
      font-size: 12px;
      color: #1890ff;
      margin: 0;
      font-style: italic;
    }
  }
}

.edit-modal-content {
  .uploaded-image-preview {
    text-align: center;
    margin-bottom: 20px;

    img {
      max-width: 100%;
      max-height: 200px;
      border-radius: 8px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }
  }
}

:deep(.ant-form-item-label > label) {
  font-weight: 500;
}

:deep(.ant-select-selector) {
  border-radius: 6px;
}

:deep(.ant-input) {
  border-radius: 6px;
}

:deep(.ant-btn) {
  border-radius: 6px;
}

:deep(.ant-upload-list-picture .ant-upload-list-item) {
  border-radius: 8px;
}
</style>
